<?php
class Database
{
    private $db_connect;
    private $queryResult;
    function __construct($config)
    {
        $this->connect($config);
    }
    function connect($config)
    {
        $this->db_connect = @mysql_connect($config["hostname"], $config["userdb"], $config["passdb"]) or
            die("Cannot Connect To MySQL Server");
        @mysql_select_db($config["dbname"], $this->db_connect) or die("Cannot Select Database MySQL Server!");
        $this->query("set names utf8");
    }
    function disconnect()
    {
        mysql_close($this->db_connect);
    }
    function query($sql)
    {
        $this->queryResult = @mysql_query($sql, $this->db_connect);
        return $this->queryResult;
    }
    function fetch($result = null)
    {
        // Nếu không truyền result query
        if ($result == null) {
            // Nếu tồn tại result query
            if (is_resource($this->queryResult))
                return mysql_fetch_assoc($this->queryResult);
            return null;
        }
        return mysql_fetch_assoc($result);
    }
    function fetch_array($result = null)
    {
        // Nếu không truyển result query
        if ($result == null) {
            if (is_resource($this->queryResult))
                while ($r = $this->fetch()) {
                    $array[] = $r;
                }
        } else { // Có truyền result
            while ($r = $this->fetch($result)) {
                $array[] = $r;
            }
        }
        return $array;
    }
    function exec_query($sql)
    {
        $this->query($sql);
        return mysql_affected_rows();
    }
    function num_rows($result = null)
    {
        if ($result == null) {
            if (is_resource($this->queryResult))
                return mysql_num_rows($this->queryResult);
        }
        return mysql_num_rows($result);
    }
    function __destruct()
    {
        $this->disconnect();
    }
}
?>  